<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单名称" prop="workorderName">
        <el-input v-model="queryParams.workorderName" placeholder="请输入工单名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" style="width: 200px;" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable>
          <el-option v-for="dict in sys_workorder_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单来源" prop="orderSource">
        <el-input v-model="queryParams.orderSource" placeholder="请输入工单来源" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="客户编码" prop="clientCode">
        <el-input v-model="queryParams.clientCode" placeholder="请输入客户编码" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker clearable v-model="queryParams.requestDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8"  v-if="!isChildrenMode">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['workorder:workorder:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['workorder:workorder:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['workorder:workorder:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['workorder:workorder:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workorderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="工单ID" align="center" prop="workorderId" /> -->
      <el-table-column label="工单编码" align="center" prop="workorderCode" />
      <el-table-column label="工单名称" align="center" prop="workorderName" />
      <el-table-column label="工单类型" align="center" prop="orderType">
        <template #default="scope">
          <dict-tag :options="sys_workorder_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="工单来源" align="center" prop="orderSource" />
      <!-- <el-table-column label="订单编号" align="center" prop="orderId" /> -->
      <el-table-column label="产品编号" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSpc" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="工单数量" align="center" prop="quantity" width="80" />
      <el-table-column label="已生产数量" align="center" prop="quantityProduced" width="120" />
      <el-table-column label="调整数量" align="center" prop="quantityChanged" width="80" />
      <!-- <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" align="center" prop="clientName" /> -->
      <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130"  v-if="!isChildrenMode" >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['workorder:workorder:edit']" v-if="scope.row.status == '草稿'">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['workorder:workorder:remove']" v-if="scope.row.status == '草稿'">删除</el-button>
          <el-button link type="primary" icon="CircleCheck" @click="handleFinish(scope.row)"
            v-hasPermi="['workorder:workorder:finished']" v-if="scope.row.status == '已确认'">完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body v-if="!isChildrenMode">
      <el-form ref="workorderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单编码" prop="workorderCode">
          <div style="display: flex; align-items: center; width: 100%;">
            <el-input v-model="form.workorderCode" placeholder="请输入工单编码" :disabled="value1" style="flex: 1;" />
            <span v-if="autoNumber" style="margin-left: 10px; white-space: nowrap;">
              <el-switch v-model="value1" @change="handleChange" /> 自动生成
            </span>
          </div>
        </el-form-item>
        <el-form-item label="工单名称" prop="workorderName">
          <el-input v-model="form.workorderName" placeholder="请输入工单名称" />
        </el-form-item>
        <el-form-item label="工单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择工单类型">
            <el-option v-for="dict in sys_workorder_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 700px;" label="工单来源" prop="orderSource">
          <el-radio-group v-model="form.orderSource" style="width: 300px;">
            <el-radio value="1" size="large">客户订单</el-radio>
            <el-radio value="2" size="large">库存备货</el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productCode">
          <el-input style="width: 550px;" v-model="form.productCode" placeholder="请输入产品编号" />

          <el-icon @click="kaii"
            style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;">
            <Search />
          </el-icon>

        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" disabled />
        </el-form-item>
        <el-form-item label="规格型号" prop="productSpc">
          <el-input v-model="form.productSpc" placeholder="请输入规格型号" disabled />
        </el-form-item>
        <el-form-item label="单位" prop="unitOfMeasure">
          <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" disabled />
        </el-form-item>
        <el-form-item label="工单数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="客户编码" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="需求日期" prop="requestDate">
          <el-date-picker clearable v-model="form.requestDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择需求日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!-- BOM组成 -->
      <el-card style="max-width: 980px" v-show="flag">
        <template #header>
          <div class="card-header">
            <button @click="listBom">BOM组成</button>
            <button @click="listBom1">物料需求</button>
          </div>
        </template>
        <el-table :data="BomData" style="width: 100%">
          <el-table-column prop="bomItemCode" label="BOM物料编号" width="180" />
          <el-table-column prop="bomItemName" label="BOM物料名称" width="180" />
          <el-table-column prop="bomItemSpec" label="规格型号" width="120" />
          <el-table-column prop="itemOrProduct" label="物料/产品" width="120" />
          <el-table-column prop="quantity" label="预计使用量" width="120" />
          <el-table-column prop="unitOfMeasure" label="单位" width="120" />
          <el-table-column prop="quantityOnhand" label="剩余库存量" width="120" v-if="showQuantityOnhand" />
          <el-table-column prop="" label="是否充足" width="80" v-if="showQuantityOnhand">
            <template #default="scope">
              <span :style="{ color: (scope.row.quantity <= scope.row.quantityOnhand) ? '' : 'red' }">
                {{ (scope.row.quantity <= scope.row.quantityOnhand) ? '是' : '否' }} </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="是否充足" width="80" v-show="showQuantityOnhand" /> -->
        </el-table>
        <template #footer>

        </template>
      </el-card>
      <template #footer>
        <div class="dialog-footer" v-show="!flag">
          <!-- 这个保存只是保存工单不保存BOM组成，但会计算出BOM组成 -->
          <el-button type="primary" @click="kai">保 存</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
        <div class="dialog-footer" v-show="flag">
          <!-- 这个保存也是保存工单信息，重新计算出BOM组成 -->
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <!-- 点击补货就是要采购增加库存，库存增加完成后，再一次计算BOM组成所需物料是否充足，点击确认就不能修改了，工单就生成了，就要扣除库存 -->
          <el-button type="success" v-if="!buhuo" @click="workOrderConfirm">确认</el-button>
          <el-button type="warning" v-if="buhuo" @click="workOrderRestock">补货</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料产品选择框 -->
    <el-dialog v-model="open2" title="物料产品选择" width="1200" :before-close="handleClose" apply-to-body v-if="!isChildrenMode">
      <div class="app-container">
        <el-container>
          <el-aside width="200px" style="background-color: white;">
            <el-table style="border: none;" v-if="refreshTable" :data="type1List" row-key="itemTypeId"
              :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              @row-click="handleCategoryClick"> <!-- 新增：点击分类行触发查询 -->
              <el-table-column align="center" prop="itemTypeName" />
            </el-table>


          </el-aside>
          <el-main>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="物料编码" prop="itemCode">
                <el-input v-model="queryParams.itemCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="物料名称" prop="itemName">
                <el-input v-model="queryParams.itemName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery1">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery1">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">

              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList1"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="物料编码" align="center" prop="itemCode" />
              <el-table-column label="物料名称" align="center" prop="itemName" />
              <el-table-column label="规格型号" align="center" prop="specification" />
              <el-table-column label="单位" align="center" prop="unitOfMeasure" />
              <el-table-column label="物料/产品" align="center" prop="itemOrProduct" />
              <el-table-column label="所属分类" align="center" prop="itemTypeName" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>

            </el-table>

            <pagination v-show="total1 > 0" :total="total1" v-model:page="itemQueryParams.pageNum"
              v-model:limit="itemQueryParams.pageSize" @pagination="getList1" />

          </el-main>

        </el-container>
        <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem">确 认</el-button>
        <el-button @click="cancel1">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Workorder">
import { listWorkorder, getWorkorder, delWorkorder, addWorkorder, updateWorkorder, getListBom, addWorkorderBom, getWorkInnerBomList } from "@/api/workorder/workorder"
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/item/item"
import { addMessage } from "@/api/system/sysmessage"
import useUserStore from "@/store/modules/user"
const useStore = useUserStore()
const currUser = ref(null)
const showQuantityOnhand = ref(false)//是否显示BOM物料库存现有量
const buhuo = ref(false)//是否补货
const autoNumber = ref(true)//自动生成工单编号按钮是否显示
//父传子接收代码相关
// -------------------------- 新增：子组件核心配置 --------------------------
// 1. 定义Props：接收父组件传递的目标工单状态（如“已确认”）
const props = defineProps({
  childrenStatus: {
    type: String,
    default: ''  // 空字符串代表“父组件模式”
  }
});

// 2. 计算属性：判断是否为“子组件模式”（childrenStatus有值则为子组件）
const isChildrenMode = computed(() => {
  return props.childrenStatus.trim() !== '';
});

// 3. 定义emit事件：子组件选中工单后，回传数据给父组件
const emit = defineEmits(['selectWorkorder']);

/** 查询物料产品管理列表 */
function getList1() {
  loading.value = true
  listItem(itemQueryParams.value).then(response => {
    itemList.value = response.rows
    total1.value = response.total
    loading.value = false
  })
}
//获取BOM组成
function listBom() {
  loading.value = true
  console.log("这什么", form.value.productId);
  //是否展示需求量和是否充足
  showQuantityOnhand.value = false
  let workorderId = form.value.productId
  getListBom(workorderId).then(response => {
    //console.log("fanhui", response);
    BomData.value = response.rows
    for (let i = 0; i < response.rows.length; i++) {
      //如果需求数量大于库存数量，则展示补货按钮
      if (response.rows[i].quantityOnhand < response.rows[i].quantity * form.value.quantity) {
        buhuo.value = true//展示补货按钮
        break;
      } else {
        buhuo.value = false//展示确认按钮
      }
    }
    //   // bomList.value = response.data
    //   // total.value = response.total
    //   // loading.value = false

  })
  loading.value = false

}

function listBom1() {
  loading.value = true
  let workorderId = form.value.productId
  showQuantityOnhand.value = true//展示BOM物料库存现有量和是否充足
  getListBom(workorderId).then(response => {
    console.log("fanhui", response);
    response.rows.forEach(item => {
      item.quantity = item.quantity * form.value.quantity
    })
    for (let i = 0; i < response.rows.length; i++) {
      //如果需求数量大于库存数量，则展示补货按钮
      if (response.rows[i].quantityOnhand < response.rows[i].quantity) {
        buhuo.value = true//展示补货按钮
        break;
      } else {
        buhuo.value = false//展示确认按钮
      }
    }
    BomData.value = response.rows
    //   // bomList.value = response.data
    //   // total.value = response.total
    //   // loading.value = false
  })
  loading.value = false
}

/** 搜索按钮操作 */
function handleQuery1() {
  itemQueryParams.value.pageNum = 1
  getList1()
}

/** 重置按钮操作 */
function resetQuery1() {
  proxy.resetForm("queryRef")
  // 清除分类ID查询条件
  itemQueryParams.value.itemTypeId = 1
  handleQuery()
}


//下拉表
import { listType1 } from "@/api/type1/type1"

/** 新增：处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  itemQueryParams.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  itemQueryParams.value.pageNum = 1
  // 执行查询
  getList1()
}


const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)


const data1 = reactive({
  queryParams1: {
  },
})

const { queryParams1 } = toRefs(data1)

/** 查询物料分类列表 */
function getList2() {
  // loading.value = true
  listType1(queryParams1.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}


getList2()

// 定义物料专用查询参数
const itemQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  itemCode: null, // 物料编码
  itemName: null, // 物料名称
  itemTypeId: 1,
});
//确认选中物料并回填
function confirmSelectedItem() {
  if (!selectedItem.value) {
    proxy.$modal.msgWarning("请选择一个物料");
    return;
  }
  // 将选中的物料信息回填到表单
  console.log(selectedItem.value);

  form.value.productCode = selectedItem.value.itemCode;
  form.value.productName = selectedItem.value.itemName;
  form.value.productSpc = selectedItem.value.specification;
  form.value.unitOfMeasure = selectedItem.value.unitOfMeasure;
  form.value.productId = selectedItem.value.itemId
  console.log(form.value);

  // 关闭物料选择框，返回工单表单
  open2.value = false;
  open.value = true;
}



function cancel1() {
  open2.value = false
  open.value = true
}

//工单编码自动生成
import { ref } from 'vue'
const value1 = ref(false)
function handleChange(value) {
  if (value) {
    form.value.workorderCode = 'WK' + new Date().getTime()
  } else {
    form.value.workorderCode = ''
  }
}
//工单来源单选
const radio1 = ref('')

const flag = ref(false)
const kai = () => {
  proxy.$refs["workorderRef"].validate(valid => {
    if (valid) {
      flag.value = true; // 显示BOM卡片
      if (form.value.workorderId != null) {
        // 已有ID：走修改（编辑场景）
        updateWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          listBom(); // 重新加载BOM
        });
      } else {
        // 无ID：走新增（添加场景）
        addWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          console.log("返回的数据",response);
          
          form.value.workorderId = response.data; 
          console.log("新增后生成的工单ID：", form.value.workorderId); // 调试用，确认有值（如123）
          listBom(); // 加载BOM
        });
      }
    }
  });
};

const kaii = () => {
  open.value = false
  open2.value = true
  getList1()
}

const qvxiao = () => {
  open2.value = false
  open.value = true
}




const { proxy } = getCurrentInstance()
const { sys_workorder_type } = proxy.useDict('sys_workorder_type')

const BomData = ref([])
const workorderBomList = ref([])//工单BOM数据,用于批量插入
const itemList = ref([]); // 用于存储物料产品列表
const selectedItem = ref('')
const workorderList = ref([])
const open = ref(false)
const open2 = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const total1 = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    quantity: null,
    orderSource: null,
    productCode: null,
    productName: null,
    productId: null,
    clientCode: null,
    clientName: null,
    requestDate: null,
    status: null,  // 新增：用于子组件模式下的状态过
  },
  rules: {
    workorderCode: [
      { required: true, message: "工单编码不能为空", trigger: "blur" }
    ],
    workorderName: [
      { required: true, message: "工单名称不能为空", trigger: "blur" }
    ],
    orderType: [
      { required: true, message: "工单类型不能为空", trigger: "change" }
    ],
    orderSource: [
      { required: true, message: "工单来源不能为空", trigger: "blur" }
    ],
    productCode: [
      { required: true, message: "产品编号不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "工单数量不能为空", trigger: "blur" }
    ],
    requestDate: [
      { required: true, message: "需求日期不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "工单数量不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询生产工单列表 */
function getList() {
  loading.value = true;
  
  // 动态拼接查询参数：子组件强制过滤status = childrenStatus
  const params = {
    ...queryParams.value,
    // 父组件模式：用原有status；子组件模式：强制用props.childrenStatus
    status: isChildrenMode.value ? props.childrenStatus : queryParams.value.status
  };

  listWorkorder(params).then(response => {
    response.rows.forEach(row => {
      row.orderSource = row.orderSource == 1 ? '客户订单' : '库存备货';
    });
    workorderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    orderSource: null,
    sourceCode: null,
    orderId: null,
    productId: null,
    productCode: null,
    productName: null,
    productSpc: null,
    unitOfMeasure: null,
    quantity: null,
    quantityProduced: null,
    quantityChanged: null,
    quantityScheduled: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    batchCode: null,
    requestDate: null,
    parentId: null,
    ancestors: null,
    finishDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("workorderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.workorderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedItem.value = selection.length > 0 ? selection[0] : null;
  if (!isChildrenMode.value) {
    ids.value = selection.map(item => item.workorderId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    selectedItem.value = selection.length > 0 ? selection[0] : null;
  } 
  // 子组件模式：必须触发emit，传递选中的工单数据
  else {
    // 核心修复：确保传递的是选中的工单对象（单选，取第一个）
    const selectedWorkorder = selection.length > 0 ? selection[0] : null;
    console.log("子组件回传的工单：", selectedWorkorder); // 调试用，确认有值
    emit('selectWorkorder', selectedWorkorder); // 触发事件回传数据
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  flag.value = false
  autoNumber.value = true;//显示自动生成工单编号按钮
  open.value = true
  title.value = "添加生产工单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  autoNumber.value = false;//隐藏自动生成工单编号按钮
  const _workorderId = row.workorderId || ids.value
  getWorkorder(_workorderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改生产工单"
    //获取工单的BOM组成数据
    listBom()
    flag.value = true
  })
  //获取工单BOM数据
  console.log(row);

}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workorderRef"].validate(valid => {
    if (valid) {
      if (form.value.workorderId != null) {
        updateWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          // open.value = false
          getList()
        })
      } else {
        addWorkorder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          console.log(response);
          form.value.workorderId = response.data
          // open.value = false
          getList()
        })
      }
    }

  })
}


//确认工单
function workOrderConfirm() {
  proxy.$modal.confirm('确认完成工单编制吗?【工单确认后无法修改】').then(async function () {
    // //获取完BOM数据就直接把该工单的BOM组成存入工单BOM组成表中
    // console.log("确认了BomData", BomData.value);
    // 清空之前的数据
    workorderBomList.value = []
    BomData.value.forEach(element => {
      //工单BOM数据对象
      const WorkorderBomData = {
        workorderId: 0,//生产工单ID
        itemId: 0,//BOM物料ID
        itemCode: "",//BOM物料编号
        itemName: "",//BOM物料名称
        itemSpc: "",//规格型号
        unitOfMeasure: "",//单位
        itemOrProduct: "",//物料产品标识
        quantity: 0,//预计使用量
      }
      // console.log("我是form.value.workorderCode", form.value.workorderCode);
      // console.log("我是", element);
      WorkorderBomData.workorderId = form.value.workorderCode
      WorkorderBomData.itemId = element.bomItemId
      WorkorderBomData.itemCode = element.bomItemCode
      WorkorderBomData.itemName = element.bomItemName
      WorkorderBomData.itemSpc = element.bomItemSpec
      WorkorderBomData.unitOfMeasure = element.unitOfMeasure
      WorkorderBomData.itemOrProduct = element.itemOrProduct
      WorkorderBomData.quantity = element.quantity
      workorderBomList.value.push(WorkorderBomData)
    });
    //console.log("workorderBomList", workorderBomList.value);
    await addWorkorderBom(workorderBomList.value).then(response => {
      console.log("添加工单BOM组成", response);
      console.log("添加工单BOM组成成功");
    })

    //console.log("打印打印", form.value);
    //确认也保存工单
    form.value.status = "已确认"
    return updateWorkorder(form.value)
  }).then(() => {
    open.value = false
    getList()
    proxy.$modal.msgSuccess("确认成功")
  }).catch(() => { })
}

//通知补货
async function workOrderRestock() {
  console.log("打印打印工单信息主要是编号", form.value.workorderCode)
  // 获取当前登录用户
  await getCurrentUser();

  const message = {
    messageTitle: "通知补货:工单编号[" + form.value.workorderCode + "]有缺货物料或产品",
    messageType: "补货通知",
    messageLevel: "一般",
    status: "未处理",
    remark: form.value.productId,
    attr1: form.value.quantity,
    createBy: currUser.value.user.userId,
    createTime: new Date(),
    updateTime: new Date(),
  }
  console.log("打印打印message", message);
  proxy.$modal.confirm('是否确认通知补货？').then(function () {
    return addMessage(message)
  }).then(() => {
    proxy.$modal.msgSuccess("通知成功")
  }).catch(() => { })
}




/** 删除按钮操作 */
function handleDelete(row) {
  const _workorderIds = row.workorderId || ids.value
  proxy.$modal.confirm('是否确认删除生产工单编号为"' + _workorderIds + '"的数据项？').then(function () {
    return delWorkorder(_workorderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/**完成工单操作，完成后无法报工 */
function handleFinish(row) {
  proxy.$modal.confirm('确认完成工单？一旦完成，此工单将无法继续报工').then(function () {
    row.status = "已完成"
    return updateWorkorder(row)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("完成成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('workorder/workorder/export', {
    ...queryParams.value
  }, `workorder_${new Date().getTime()}.xlsx`)
}
//  // 获取当前登录用户 注意需要在 async 函数中使用 await
async function getCurrentUser() {
  try {
    currUser.value = await useStore.getInfo();

    console.log("当前登录用户", currUser.value.user.userId);
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
}
getList()

</script>
